package com.surverycomp.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

@PersistenceCapable
public class Challenge {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	@Persistent
	private String question;
	@Persistent
	private List<String> answers = new ArrayList<String>();
	@Persistent
	private String answer;
	@Persistent
	private String name;

	public Challenge(String challenge, HttpServletRequest req) {
		this.question = req.getParameter(challenge + "-question");
		this.name = req.getParameter(challenge + "-name");

		String rightAnswer = req.getParameter(challenge + "-right-answer");
		this.answer = rightAnswer;
		String s;
		int counter = 0;

		while ((s = req.getParameter(challenge + "-wrong-answer" + ++counter)) != null) {
			answers.add(s);
		}
	}

	public Challenge(String question, List<String> answers, String answer,
			String name) {
		this.question = question;
		this.answers.addAll(answers);
		this.answer = answer;
		this.name = name;
	}

	@SuppressWarnings("unchecked")
	public Challenge(Entity value) {
		this.answer = (String) value.getProperty("answer");
		this.name = (String) value.getProperty("name");
		this.answers.addAll((Collection<? extends String>) value
				.getProperty("answers"));
		this.question = (String) value.getProperty("question");
	}

	public String getQuestion() {
		return question;
	}

	public String getAnswer() {
		return answer;
	}

	public JSONObject getJSON() throws JSONException {
		JSONObject object = new JSONObject().put("question", question)
				.put("name", name).put("rightAnswer", answer)
				.put("answers", answers).put("id", key.getId());
		return object;
	}

	public List<String> getAnswers() {
		return answers;
	}

	public String getName() {
		return name;
	}

	public Key getKey() {
		return key;
	}

	@Override
	public boolean equals(Object other) {
		if (other == null)
			return false;
		if (other instanceof Challenge) {

			Challenge challenge = (Challenge) other;
			return name.equals(challenge.name)
					&& answer.equals(challenge.answer)
					&& answers.equals(challenge.answers);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return (int) (name.hashCode() * question.hashCode() * answer.hashCode());
	}

	@Override
	public String toString() {
		return "[name: {" + name + "}, id:{" + key + "}]";
	}

	public void setKey(Key key) {
		this.key = key;
	}
}